package com.tyut.rongxiaotong.interceptor;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.tyut.rongxiaotong.common.Result;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @Title: CheckTokenInterceptor
 * @Author Wood
 * @Package com.tyut.rongxiaotong.interceptor
 * @Date 2025/5/31 15:46
 * @description: 检查用户是否已经登录携带token
 */
@Component
public class CheckTokenInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String method = request.getMethod();
        if ("OPTIONS".equalsIgnoreCase(method)){
            return true;
        }

        String token = request.getHeader("token");
        if (token == null){
            Result result = new Result(500,"请先登录!",null);
            doResponse(response,result);
        }

        return false;
    }

    private void doResponse(HttpServletResponse response, Result result) throws IOException {
        response.setContentType("application/json");
        response.setCharacterEncoding("utf-8");
        PrintWriter out = response.getWriter();
        String s = new ObjectMapper().writeValueAsString(result);
        out.print(s);
        out.flush();
        out.close();
    }
}
